<!--
 * @Author: bear
 * @Date: 2022-08-02 14:00:31
 * @LastEditors: bear
 * @LastEditTime: 2022-08-03 16:44:54
 * @Description: your project
 * @version: 1.0
-->
<template>
  <div class="operationFile">
    <div class="box borderCorner">
      <span @click="choseFile">选择文件</span>
    </div>
    <div class="file borderCorner">
      <span v-text="fileContent"></span>
    </div>
    <div class="box borderCorner">
      <span @click="choseMoreFile">选择多文件</span>
    </div>
    <div class="file borderCorner">
      <span v-for="(item, index) in fileMoreContent" :key="index">{{
        item
      }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
const { dialog } = require("electron").remote;
// 引入node fs模块
const fs = require("fs");
// 文件内容展示变量
const fileContent = ref();
const fileMoreContent = ref([]);
const choseFile = () => {
  // 选择要读取的文件
  dialog.showOpenDialog().then((res) => {
    console.log(res.filePaths[0]);
    // 单文件读取
    res.filePaths.length == 1 && readFileContent(res.filePaths[0]);
  });
};
// 读取单文件内容
const readFileContent = (filePath) => {
  fs.readFile(filePath, { encoding: "utf-8" }, (err, result) => {
    if (err) {
      console.log(err, "读取文件内容失败");
    } else {
      console.log(result);
      fileContent.value = result;
    }
  });
};
// 选择多文件
const choseMoreFile = async () => {
  // 选择要读取的文件
  dialog.showOpenDialog({ properties: ["multiSelections"] }).then((res) => {
    // 多文件读取
    res.filePaths.length > 1 &&
      res.filePaths.map((val) => {
        readMoreFileContent(val).then((fileText) => {
          console.log(fileText);
          fileMoreContent.value.push(fileText);
        });
      });
  });
};
// 读取多文件内容
const readMoreFileContent = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, { encoding: "utf-8" }, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};
</script>
<style scoped>
@import url("../layout/public/common.css");
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #108ba1;
  padding: 10px 20px;
  font-size: 22px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #0adfff;
  line-height: 40px;
  cursor: pointer;
}
</style>
